import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'organization_form.dart';
import 'organization_model.dart';
import '../../core/base/base_view_model.dart';
import 'organization_list_view_model.dart';

class OrganizationListView extends StatelessWidget {
  const OrganizationListView({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (_) => OrganizationListViewModel(),
      child: const _OrganizationListViewContent(),
    );
  }
}

class _OrganizationListViewContent extends StatefulWidget {
  const _OrganizationListViewContent({Key? key}) : super(key: key);

  @override
  _OrganizationListViewContentState createState() => _OrganizationListViewContentState();
}

class _OrganizationListViewContentState extends State<_OrganizationListViewContent> {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      context.read<OrganizationListViewModel>().fetchOrganizations();
    });
  }

  void _showOrganizationForm(BuildContext context, OrganizationListViewModel viewModel, {OrganizationModel? organization}) {
    showDialog(
      context: context,
      builder: (dialogContext) => Dialog(
        child: Container(
          width: 600,
          padding: const EdgeInsets.all(16),
          child: SingleChildScrollView(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(
                  organization == null ? '添加机构' : '编辑机构',
                  style: Theme.of(dialogContext).textTheme.headlineSmall,
                ),
                const SizedBox(height: 16),
                OrganizationForm(
                  organization: organization,
                  onSubmit: (data) {
                    if (organization != null) {
                      viewModel.updateOrganization(organization.id, data);
                    } else {
                      viewModel.createOrganization(data);
                    }
                    Navigator.of(dialogContext).pop();
                  },
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('机构管理'),
        actions: [
          IconButton(
            icon: const Icon(Icons.add),
            onPressed: () => _showOrganizationForm(context, context.read<OrganizationListViewModel>()),
          ),
        ],
      ),
      body: Column(
        children: [
          Padding(
            padding: const EdgeInsets.all(16),
            child: TextField(
              decoration: const InputDecoration(
                labelText: '搜索',
                prefixIcon: Icon(Icons.search),
                border: OutlineInputBorder(),
              ),
              onChanged: (value) {
                context.read<OrganizationListViewModel>().setSearchKeyword(value);
              },
            ),
          ),
          Expanded(
            child: Consumer<OrganizationListViewModel>(
              builder: (context, viewModel, _) {
                if (viewModel.isBusy) {
                  return const Center(child: CircularProgressIndicator());
                }

                if (viewModel.state == ViewState.error) {
                  return Center(
                    child: Text(
                      viewModel.errorMessage ?? '加载失败',
                      style: const TextStyle(color: Colors.red),
                    ),
                  );
                }

                if (viewModel.filteredOrganizations.isEmpty) {
                  return const Center(child: Text('暂无数据'));
                }

                return ListView.builder(
                  itemCount: viewModel.filteredOrganizations.length + (viewModel.hasMore ? 1 : 0),
                  itemBuilder: (context, index) {
                    if (index == viewModel.filteredOrganizations.length) {
                      if (viewModel.isBusy) {
                        return const Center(
                          child: Padding(
                            padding: EdgeInsets.all(16.0),
                            child: CircularProgressIndicator(),
                          ),
                        );
                      } else {
                        return const Center(
                          child: Padding(
                            padding: EdgeInsets.all(16.0),
                            child: CircularProgressIndicator(),
                          ),
                        );
                      }
                    }
                    final organization = viewModel.filteredOrganizations[index];
                    return Card(
                      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                      child: ListTile(
                        title: Text(organization.name),
                        subtitle: Text('联系人：${organization.contactPerson}\n联系方式：${organization.contactInfo}\n参数：${organization.params}'),
                        trailing: Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            IconButton(
                              icon: const Icon(Icons.edit),
                              onPressed: () => _showOrganizationForm(context,context.read<OrganizationListViewModel>(), organization: organization),
                            ),
                            IconButton(
                              icon: const Icon(Icons.delete),
                              onPressed: () {
                                showDialog(
                                  context: context,
                                  builder: (context) => AlertDialog(
                                    title: const Text('确认删除'),
                                    content: const Text('确定要删除该机构吗？'),
                                    actions: [
                                      TextButton(
                                        onPressed: () => Navigator.of(context).pop(),
                                        child: const Text('取消'),
                                      ),
                                      TextButton(
                                        onPressed: () {
                                          Navigator.of(context).pop();
                                          viewModel.deleteOrganization(organization.id);
                                        },
                                        child: const Text('确定'),
                                      ),
                                    ],
                                  ),
                                );
                              },
                            ),
                          ],
                        ),
                      ),
                    );
                  },
                );
              },
            ),
          ),
        ],
      ),
    );
  }
}